package com.xqls.biz.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xqls.bean.BlockBean;
import com.xqls.bean.UserBean;
import com.xqls.biz.BlockBiz;
import com.xqls.redis.Constants;
import com.xqls.redis.RedisCache;
import com.xqls.redis.RedisKeyEnum;
import com.xqls.service.BlockService;
import com.xqls.service.CompanyService;
import com.xqls.util.CommonResult;

@Service
public class BlockBizImpl implements BlockBiz{
	
	private static Logger logger = Logger.getLogger(BlockBizImpl.class);

	@Autowired private BlockService blockService;
	@Autowired private CompanyService companyService;
	
	@Autowired
	private RedisCache<String, Object> redisCache;
	
	@Override
	public CommonResult edit(BlockBean bean){
		CommonResult result = new CommonResult();
		boolean success = false;
		try {
			if(bean != null){
				if(bean.getBlockId() != null){
					success = blockService.update(bean);
				}else{
					success = blockService.add(bean);
				}
				result.setIsSuccess(success);
			}
		} catch (Exception e) {
			logger.error("编辑区块异常",e);
		}
		return result;
	}
	
	@Override
	public CommonResult remove(Integer key){
		boolean success = false;
		try {
			success = blockService.delete(key);
			if(success){
				success = companyService.deleteByBlockId(key);
			}
		} catch (Exception e) {
			logger.error("删除区块及所属企业异常",e);
		}
		return new CommonResult(success);
	}
	
	@Override
	public List<BlockBean> queryList(Integer key){
		List<BlockBean> beans = null;
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			BlockBean block = blockService.queryByKey(key);
			if(block != null){
				map.put("blockUrl", block.getBlockUrl());
				beans = blockService.queryList(map);
			}
		} catch (Exception e) {
			logger.error("查询区块异常",e);
		}
		return beans;
	}
	
	@Override
	public List<BlockBean> queryList(boolean isAll){
		List<BlockBean> beans = null;
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			if(isAll){
				Subject subject = SecurityUtils.getSubject();
				String username = subject.getPrincipal().toString();
				UserBean user = (UserBean) redisCache.get(Constants.getRedisKey(RedisKeyEnum.USER_SESSION, username));
				map.put("blockUrl", user.getBlockId()+";");
			}
			beans = blockService.queryList(map);
		} catch (Exception e) {
			logger.error("查询区块异常",e);
		}
		return beans;
	}
}
